<template>
  <div class="wrapper" id="devicePage">
    <el-form :inline="true" class="ur-form mb-3 d-flex" style="height: 54px;">
      <el-form-item label="责任区">
       <!-- <el-select @change="currentPage=1,search()" class="w150 " size="small" v-model="regionId">
          <el-option :value="-1" label="全部"></el-option>
          <el-option label="新区" :value="1" ></el-option>
        </el-select>-->
        <region-cascader :regionIdStr="regionId" @getRegionId="getRegionId"></region-cascader>
      </el-form-item>
      <el-form-item label="状态">
        <el-select class="w120 " size="small" v-model="BoxState">
          <el-option :value="-1" label="全部"></el-option>
          <el-option :key="index" :label="item" :value="index" v-for="(item,index) in global.BoxStates"></el-option>
        </el-select>
      </el-form-item>
      <el-input @blur="currentPage=1,search()" class="input-with-select w220" placeholder="请输入内容" size="small" v-model="searchTxt">
        <el-button @click="currentPage=1,search()" class="ur-btn ur-btn-primary" slot="append">
          <i class="iconfont icon-search"></i>查询
        </el-button>
      </el-input>
      <el-button @click="showBoxAdd=true,box.Id=0" class="ur-btn ur-btn-primary ml-1"><i
        class="iconfont icon-add"></i>添加
      </el-button>
      <el-button @click="batchBoxDialog=true" class="ur-btn ur-btn-primary ml-2"><i class="iconfont icon-add"></i>批量新增</el-button>
      <el-button @click="exportData" class="ur-btn ur-btn-primary ml-2"><i class="iconfont icon-dowload"></i>导出</el-button>
      <el-button @click="exportData" class="ur-btn ur-btn-primary ml-2"><i class="iconfont icon-yunxing"></i>通讯测试</el-button>
    </el-form>
    <!--表格:cell-class-name="api.fixedCell" -->
    <el-table class="ur-table" stripe :data="boxs" :height="clientHeight-210" @row-click="rowClick"
              @selection-change="selsChange"
              highlight-current-row  style="width: 100%;">
      <el-table-column align="center" fixed type="selection" width="40"></el-table-column>
      <el-table-column :index="indexMethod" align="center" fixed label="序号" type="index" width="45"></el-table-column>
      <el-table-column :fixed="v.field=='No'" :key="index" :label="v.title" :min-width="v.width"
                       :prop="v.field" align="center" v-for="(v,index) in columns">
        <template slot-scope="scope">
          <span v-if="v.field=='InstallType'">{{global.BoxTypes[scope.row[v.field]-1]}}</span>
          <span v-if="v.field=='BoxState'" :class="{'text-success':scope.row.BoxState==1}">{{global.BoxStates[scope.row[v.field]]}}</span>
          <span v-else-if="v.field=='InstallDate'||v.field=='RtuInstallDate'">{{api.formatDate(scope.row[v.field])}}</span>
          <span v-else-if="v.field=='RtuInstalled'">
            <i class='circle' :class="scope.row[v.field]==1?'warning':'default'"></i>
            {{scope.row[v.field]==1?'有':'无'}}RTU
          </span>
          <i @click="showMap=true,box=scope.row" class="font22 iconfont icon-gis txt_blue3"
             v-else-if="v.field=='localtion'"></i>
          <span v-else>{{scope.row[v.field]}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="result" label="通讯" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.result==1"><i class='circle success'></i>成功</template>
          <template v-else-if="scope.row.result===0"><i class="circle error" ></i>失败</template>
          <template v-else>{{scope.row.result}}</template>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" width="90">
        <template slot="header" slot-scope="scope">下属设备</template>
        <template slot-scope="scope">
          <el-button class="ur-btn ur-btn-primary d-inline-block" @click="handlesubDevice(scope.row)">
            <i class="font18 iconfont icon-xianshi" ></i>查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" width="110">
        <template slot="header" slot-scope="scope">操作</template>
        <template slot-scope="scope">
          <el-button class="ur-btn ur-btn-waring d-inline-block">
            <i class="font18 iconfont icon-edit mr-0" @click="handleEdit(scope.$index, scope.row,true)"></i>
          </el-button>
          <el-button class="ur-btn ur-btn-danger d-inline-block">
            <i class="font18 iconfont icon-delete mr-0" @click="handleDel(scope.$index, scope.row)"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div class="mt-3">
      <el-button :disabled="sels.length===0" @click="batchRemove" class="float-left" type="danger">批量删除</el-button>
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[100,200,500,1000]"
                     :total="total"
                     @current-change="handleCurrentChange" @size-change="handleSizeChange" class="float-right "
                     layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    </div>

    <!--地图-->
    <el-dialog class="ur-form-dialog" :visible.sync="showMap" @close="search" title="获取位置" v-el-drag-dialog width="900px">
      <template v-if="showMap">
        <u-map :box="box" :boxs="boxs" :iconType="1" @getLngLat="getLngLat($event)"></u-map>
      </template>
    </el-dialog>
    <el-dialog class="ur-form-dialog" :visible.sync="showBoxAdd" @close="search" title="添加控制箱" v-el-drag-dialog width="1200px">
      <template v-if="showBoxAdd">
        <box-add :boxId="box.Id" @close="showBoxAdd=false"></box-add>
      </template>
    </el-dialog>

    <!--批量控制箱-->
    <el-dialog class="ur-form-dialog" :visible.sync="batchBoxDialog" title="批量新增" top="15%" v-el-drag-dialog width="450px">
      <div class="p-4" v-if="batchBoxDialog">
        <el-form class="ur-form " :inline="true" ref="uploadForm" style="background: transparent;">
          <el-form-item label="选择附件" label-width="120px" label-position="right" class="w300 mb-2" >
            <div class="p_relative ur-file w160">
              <input class=" file" type="file" style="line-height: 20px;" accept=".xlsx" @change="changeFiles">
            </div>
          </el-form-item>
        </el-form>
        <p class="mb-4" style="line-height: 20px;color: #44FF95;">注：文件要求类型 （注：只支持xlsx格式文件 导入前请先下载模板按照页面上显示信息填写以及请先阅读参数输入规则说明！）</p>
        <div class="d-flex align-items-center justify-content-center">
          <el-button @click="downloadFile" class="ur-btn ur-btn-primary"><i class="iconfont icon-dowload"></i>下载模板
          </el-button>
          <el-button @click="saveBatchBox" class="ur-btn ur-btn-primary"><i class="iconfont icon-sure"></i>确定
          </el-button>
        </div>
      </div>
    </el-dialog>

<!--    控制箱下属设备-->
    <el-dialog class="ur-form-dialog" :visible.sync="subDeviceDialog" title="控制箱下属设备" top="15%" v-el-drag-dialog width="460px">
      <sub-device></sub-device>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import {mapState} from 'vuex'
  import api from 'api/api'
  import fetch from "api/fetch"
  import uMap from 'base/map/map'
  import regionCascader from 'base/region-cascader'
  import elDragDialog from 'directive/el-dragDialog'
  import boxAdd from './box-add'
  import subDevice from './sub-device'

  export default {
    directives: {elDragDialog},
    components: {
      uMap,
      boxAdd,
      regionCascader,
      subDevice
    },
    props: {},
    data() {
      return {
        BoxState: -1,
        regionId: '',
        regions: [],
        total: 0,
        currentPage: 1,
        pageSize: 100,
        searchTxt: null,
        columns: [
          {field: "No", title: "控制箱编号", width: '120'},
          {field: "AreaName", title: "责任区", width: '130'},
          {field: "Location", title: "安装地址", width: '200'},
          {field: "Manufacturer", title: "生产厂家", width: null},
          {field: "InstallType", title: "安装类型", width: '90'},
          {field: "Model", title: "控制箱型号", width: '90'},
          {field: "InstallDate", title: "控制箱安装日期", width: '110'},
          {field: "RtuInstalled", title: "是否有RTU", width: '80'},
          {field: "RtuInstallDate", title: "RTU安装日期", width: '110'},
          {field: "BoxState", title: "状态", width: '80'},
          {field: "localtion", title: "定位", width: '60'},
          {field: "DevAddr", title: "设备地址", width: '160'},
        ],
        sels: [],
        boxs:[],
        box: {},
        api: api,
        showMap: false,
        showBoxAdd: false,
        showLightBatchAdd: false,
        batchBoxDialog: false,
        subDeviceDialog:false,
        formData: new FormData(),
      }
    },
    watch: {},
    computed: {
      getGidData() {
        if (this.boxs.length) {
          return this.boxs.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        }
      },
      ...mapState({
        clientHeight: state => state.comm.clientHeight,
        clientWidth: state => state.comm.clientWidth,
        limits: state => state.user.userInfo.limits
      }),
    },
    methods: {
      getRegionId(v){
        this.regionId = v.join(',')
      },
      downloadFile() {
        window.open(api.ajaxServe + '批量导入控制箱模板.xlsx')
      },
      changeFiles() {
        if (this.formData.has("file")) {
          this.formData.delete("file")
        }
        let files = event.target.files
        for (let i = 0; i < files.length; i++) {
          this.formData.append('file', files[i])
        }
      },
      saveBatchBox() {
        // this.$refs.uploadForm.reset()
        if (this.formData.get('file')) {
          api.httpFormData('/DevRtu/BatchInsert', this.formData)
              .then(r => {
                this.$message.success({showClose: true, message: '批量导入成功'})
                this.search()
                this.batchBoxDialog = false
              })
        } else {
          this.$message.warning({showClose: true, message: '未选择文件'})
        }
      },
      exportData() {
        api.fetchFile('/DevRtu/ExportBoxInfo', {
          reagionId: this.regionId,
          boxState: this.BoxState == -1 ? null : this.BoxState,
          value: this.searchTxt
        })
            .then(r => {
              fetch.saveFile(r, '控制箱列表', ['', ''])
            })
      },
      batchAddPole() {
        if (this.box.Id) {
          this.showLightBatchAdd = true
        } else {
          this.$message.warning('请先选中一个控制箱!')
        }
      },
      getLngLat(v) {
        this.showMap = false
      },
      indexMethod(index) {
        return index + 1
      },
      rowClick(row, event, column) {
        this.box = row
      },
      selsChange(sels) {
        this.sels = sels
        this.sels.splice(1, 0)
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.currentPage = 1
        this.search()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.search()
      },
      handlesubDevice(row){
        this.subDeviceDialog=true
      },
      handleEdit(index, row, isEdit) {
        this.box = row
        this.showBoxAdd = true
      },
      handleDel(index, row) {
        this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
            .then(() => {
              api.fetch('/DevRtu/Delete', [row.BoxId])
                  .then(r => {
                    this.$message.success({showClose: true, message: '删除成功'})
                    this.search()
                  })
            })
      },
      batchRemove() {
        let ids = []
        this.sels.map(r => {
          ids.push(r.Id)
        })
        this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
            .then(() => {
              api.fetch('/DevRtu/Delete', ids)
                  .then(r => {
                    this.$message.success('删除成功')
                    this.search()
                  })
            })
      },
      search() {
        this.boxs=[]
        for(let i=0;i<3;i++){
          let o={AreaId: 1, AreaName: "川沙", BoxId: 1, BoxState: 1, Capacity: 380,
            ControlRange: 1, Created: "2017-12-11 17:12:19", Deleted: 0,
            DevAddr: "0000000000008134", EnergySaving: "1", Id: 1, InlineNum: 1,
            InstallDate: "2009-09-09 00:00:00", InstallType: 1, Lat: 31.2009832417, Lng: 121.625496199,
            Location: "申江路（高科中路-西沟港）", Maintenance: "", Manufacturer: "求锦", MeterNo: "",
            Model: "GCK", No: "20446", OutlineNum: 2, Owner: 1, Phase: 3, Poles: 19,
            ProjectAccount: "", RoadEnd: "申江路（高科中路-西沟港）", RoadNature: 5, RoadSection: "申江路（高科中路-西沟港）",
            RoadStart: "申江路（高科中路-西沟港）", RtuId: 1, RtuInstallDate: "2018-01-02 00:00:00", RtuInstalled: 1,
            RunDate: "2018-01-02 00:00:00", Updated: "2020-04-14 21:10:12", UserNumber: "", WellInstalled: 0,result:1};
          this.boxs.push(o)
        }
        this.boxs.splice(0,0);
      },
      queryRegion() {
      },
    },
    created() {
      this.queryRegion()
      this.search()
    },
    mounted() {
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
</style>
